package SlidingWindow.Medium;

public class LC1493 {
    public int longestSubarray(int[] nums) {
        if (nums == null || nums.length == 0) return 0;

        int n = nums.length;
        int left = 0, right = 1;
        int slackness = nums[left] == 0 ? 0 : 1;
        int maxLength = 0, length;
        for (; right < n; right++) {
            if (nums[right] == 0) {
                if (slackness == 0) {
                    // 左指针左移，直到释放一个0
                    while (left < right && nums[left] == 1) left++;
                    if (left < right) left++; // 左右指针没重合，那么nums[left]==0，左指针右移以释放0
                } else slackness = 0;
            }
            length = right - left + 1 - 1; // +1是为了正确计算子数组的长度，-1是因为始终要删除一个元素：如果数组中有0则删去0；没有0则删去1
            maxLength = Math.max(length, maxLength);
        }

        return maxLength;
    }
}
